/*
 * @depends component.js, Panel.js
 */
QFinance.component.TransactionsImportPanel = Ext.extend( QFinance.ui.Panel, {
    // Localization
    welcomeText: 'Welcome, bla bla bla',
    bankText: 'Bank',
    bankEmptyText: 'Select a bank...',
    fileText: 'File',
    fileEmptyText: 'Select a file',
    accountText: 'Account',
    accountEmptyText: 'Select an account',
    finishButtonText: 'Finish', 
    finishText: '{0} transactions are ready to be imported into the {1}, click \'{2}\' to make them permanent.',    
	
    // State
    imported: false,
	
    // Components
    wizard: null,	
    formPanel: null,
    transactionsEditPanel: null,
    accountStore: null,
	
    constructor: function(config) {
        Ext.apply(this, config);
		
        this.addEvents(['importData']);		
		
        QFinance.component.TransactionsImportPanel.superclass.constructor.call(this);
    },
	
    initComponent: function() {
        this.wizard = this.getWizardItem();
				
        Ext.apply(this, {
            layout: 'fit',			
            items: [ this.wizard ]
        });
		
        QFinance.component.TransactionsImportPanel.superclass.initComponent.call(this);
    },
	
    getWizardItem: function() {
        var wizardItem = new QFinance.ui.WizardPanel({            
            listeners: {
                scope: this,
                beforeitemchange: function( wizard, fromItem, toItem ) {
                    var canChange = true;
                    if (fromItem.itemName == 'Parameters' && toItem.itemName == 'Transactions') {
                        if (this.formPanel.getForm().isValid())
                            canChange = true;
                        else							
                            canChange = false;
                    }
                    return canChange;
                },
                itemchange: function( wizard, fromItem, toItem ) {
                    if (fromItem.itemName == 'Parameters' && toItem.itemName == 'Transactions') {
                        var sendFileID = this.getProcessStatusManager().start([this.transactionEditPanel]);
                        this.checkTemporaryTransactionsGhosts(function() {
                            this.formPanel.getForm().submit({
                                scope: this,
                                success: function(form, action) {
                                    this.getProcessStatusManager().success(sendFileID);
                                    this.imported = false;
                                    this.transactionsEditPanel.setContextAccountID(parseInt(this.formPanel.getForm().findField('accountID').getValue()));
                                    this.transactionsEditPanel.setTemporaryTransactionID(action.result.temporaryID);				
                                },
                                failure: function(form, action) {
                                    var message = '';
                                    var where = '';
                                    switch (action.failureType) {			
                                        case Ext.form.Action.CLIENT_INVALID:
                                            message = 'Form fields may not be submitted with invalid values';			    
                                            break;
                                        case Ext.form.Action.CONNECT_FAILURE:
                                            message = 'Ajax communication failed';
                                            break;
                                        case Ext.form.Action.SERVER_INVALID:
                                            message = action.result.message;
                                            if (action.result.type == 'exception')
                                                where = action.result.where;
                                            break;
                                    }
                                    this.getProcessStatusManager().error(sendFileID, message);
                                    QFinance.service.DeveloperService.log('Submit failure: ' + message + ' where\n' + where);
                                }								
                            });	
                        }, this);
                    } else if (fromItem.itemName == 'Transactions' && toItem.itemName == 'Finish') {
                        toItem.items.get(0).el.dom.innerText = String.format(this.finishText, this.transactionsEditPanel.store.getTotalCount(), this.formPanel.getForm().findField('accountID').getRawValue(), this.finishButtonText);
                    }					
                },
                finish: function( wizard ) {
                    this.doImportData();
                }
            }
        });
		
        wizardItem.items.add(new Ext.Panel({
            itemName: 'Parameters',
            layout: {
                type: 'vbox',
                pack: 'start',
                align: 'stretch',
                defaultMargins: '10'
            },            	    
            defaults: {
                frame: false,  
                border: false
            },
            items: [{
                flex: 1,
                autoScroll: true,
                html: this.welcomeText
            },{       
                flex: 1,
                layout: {
                    type: 'vbox',
                    pack: 'start',
                    align: 'center',
                    defaultMargins: '10'
                },      
                defaults: {
                    frame: false,  
                    border: false
                },
                items: [ this.formPanel = new Ext.form.FormPanel({
                    width: 300,
                    fileUpload: true,
                    labelWidth: 50,
                    defaults: {
                        anchor: '100%',
                        allowBlank: false
                    },                	    	
                    items: [{
                        xtype: 'combo',
                        fieldLabel: this.bankText,
                        typeAhead: true,
                        triggerAction: 'all',
                        emptyText: this.bankEmptyText,
                        selectOnFocus: true,
                        forceSelection: true,
                        store: [
                        ['1', 'Banco Real'],
                        ['2', 'Banco Itaú'],
                        ['3', 'Caixa']
                        ],
                        hiddenName: 'bankID',
                        name: 'bank'
                    },{
                        xtype: 'combo',
                        fieldLabel: this.accountText,	    				
                        store: this.accountStore = new Ext.data.DirectStore({
                            directFn: QFinance.Remoting.AccountAction.getByAccountType,
                            paramsAsHash: false,
                            autoLoad: true,
                            paramOrder: [ 'type' ],
                            baseParams: {
                                type: '1'
                            },
                            idProperty: 'id',
                            root: 'data',
                            successProperty: 'success',
                            fields: [
                            {
                                name: 'id',
                                type: 'int'
                            },
                            {
                                name: 'accountName'	    		    
                            },
                            {
                                name: 'accountType'
                            }
                            ],
                            listeners: {
                                scope: this,
                                beforeload: function(store, options) {
                                    store.id = this.getProcessStatusManager().start([this]);
                                },				
                                load: function(store, records, options) {
                                    this.getProcessStatusManager().success(store.id);
                                },
                                exception: function(dataProxy, type, action, options, response, arg ) {
                                    var message = '';
                                    var where = '';
                                    if (response.result) {
                                        message = response.result.message;
                                        if (response.result.type == 'exception')
                                            where = response.result.where;
                                    } else {
                                        message = response.message;
                                    }
                                    this.getProcessStatusManager().error(this.accountStore.id, message);                                    
                                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);
                                }
                            }						
                        }),
                        typeAhead: true,
                        triggerAction: 'all',
                        emptyText: this.accountEmptyText,
                        selectOnFocus: true,
                        valueField: 'id',
                        displayField: 'accountName',
                        hiddenName: 'accountID',
                        forceSelection: true,
                        mode: 'local',	    	        	
                        name: 'account'
                    },{
                        xtype: 'fileuploadfield',
                        emptyText: this.fileEmptyText,
                        fieldLabel: this.fileText,
                        buttonText: '',
                        buttonCfg: {
                            iconCls: 'fugue-document--plus'
                        },
                        name: 'file'
                    }],
                    api: {
                        submit: QFinance.Remoting.TransactionsImportPanelAction.importData	            		
                    }	
                })]
            }]
        }));
		
        wizardItem.items.add(new Ext.Panel({
            itemName: 'Transactions',
            layout: 'fit',
            items: [ this.transactionsEditPanel = new QFinance.component.TransactionsEditPanel() ]
        }));
		
        wizardItem.items.add(new Ext.Panel({
            itemName: 'Finish',
            layout: {
                type: 'vbox',
                pack: 'start',
                align: 'stretch',
                defaultMargins: '10'
            },            	    
            defaults: {
                frame: false,  
                border: false
            },
            items: [{
                flex: 1,
                autoScroll: true,
                html: this.finishText
            }] 
        }));
		
        return wizardItem;
    },
	
    doImportData: function() {
        var importDataID = this.getProcessStatusManager().start([this]);        
        QFinance.Remoting.TransactionsImportPanelAction.makePermanent(this.transactionsEditPanel.temporaryID, function(result, event) {
            var message = '';
            var where = '';
            var failure = false;
			
            if (result) {
                if (result.success) {
                    this.getProcessStatusManager().success(importDataID);
                    this.imported = true;
                    this.fireEvent('importData');		
                } else {
                    failure = true;						
                    message = result.message;
                    if (result.type == 'exception')
                        where = result.where;
                }            
            } else {
                failure = true;
                message = event.message;
            }
			
            if (failure) {
                this.getProcessStatusManager().error(importDataID, message);
                QFinance.service.DeveloperService.log('Direct call failure: ' + message + ' where\n' + where);
            }           		
        }, this);		
    },
	
    checkTemporaryTransactionsGhosts: function(callback, scope) {
        if (this.transactionsEditPanel.temporaryID && !this.imported) {
            var temporaryTransactionsGhostsID = this.getProcessStatusManager().start([this]);
            QFinance.Remoting.TransactionsImportPanelAction.removeTemporaryTransactions(this.transactionsEditPanel.temporaryID, function(result, event) {
                var message = '';
                var where = '';
                var failure = false;
				
                if (result) {
                    if (result.success) {
                        this.getProcessStatusManager().success(temporaryTransactionsGhostsID);                        
                        if (callback) callback.call(scope||this);		
                    } else {
                        failure = true;						
                        message = result.message;
                        if (result.type == 'exception')
                            where = result.where;
                    }            
                } else {
                    failure = true;
                    message = event.message;
                }
				
                if (failure) {
                    this.getProcessStatusManager().error(temporaryTransactionsGhostsID, message);
                    QFinance.service.DeveloperService.log('Direct call failure: ' + message + ' where\n' + where);
                }
            }, this);			
        } else {
            if (callback) callback.call(scope||this);
        }
    }
});
Ext.reg('QFinance.component.TransactionsImportPanel', QFinance.component.TransactionsImportPanel);